from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from services.auth_service import require_user
from models.user_models import UserType

from services.payment_service import get_or_create_payment

# 导入相关的模型和schemas
from models.medicine_record_model import RecordOfMedicine
from models.medicine_model import Medicine  # 新增导入药品模型
from schemas.medicine_record_schemas import RecordCreate, RecordUpdate

router = APIRouter(prefix="/medicine-records")

# 获取所有药品发放记录（管理员权限）
@router.get("/")
def get_all_records(db: Session = Depends(get_db),
                   user=Depends(require_user(UserType.ADMIN))):
    return db.query(RecordOfMedicine).all()

# 获取单个药品发放记录（管理员或药师权限）
@router.get("/{record_id}")
def get_record(record_id: int, 
              db: Session = Depends(get_db),
              user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    record = db.query(RecordOfMedicine).filter_by(ID=record_id).first()
    if not record:
        raise HTTPException(status_code=404, detail="记录不存在")
    return record

# 创建药品发放记录（管理员或药师权限）
@router.post("/")
def create_record(record: RecordCreate,
                db: Session = Depends(get_db),
                user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    try:
        # 开始事务
        db.begin()
        
        # 1. 检查药品库存是否充足
        medicine = db.query(Medicine).filter_by(ID=record.medicine_ID).first()
        if not medicine:
            raise HTTPException(status_code=404, detail="药品不存在")
        if medicine.stock < record.number:
            raise HTTPException(status_code=400, detail="药品库存不足")
        
        # 2. 创建发放记录
        db_record = RecordOfMedicine(**record.model_dump())
        db.add(db_record)
        
        # 3. 更新药品库存
        medicine.stock -= record.number
        
        # 4. 查找或创建支付记录并更新药品费用
        payment = get_or_create_payment(db, record.patient_ID, record.con_date)
        
        # 5. 更新支付记录中的药品费用
        payment.medi_expense += record.total_price  # 累加药品费用
        payment.total_expense = payment.con_expense + payment.medi_expense
        
        # 提交所有更改
        db.commit()
        db.refresh(db_record)
        return db_record
        
    except HTTPException as he:
        db.rollback()
        raise he
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=500, 
            detail=f"创建发药记录失败: {str(e)}"
        )

# 更新药品发放记录（管理员或药师权限）
@router.put("/{record_id}")
def update_record(record_id: int,
                 record_update: RecordUpdate,
                 db: Session = Depends(get_db),
                 user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    try:
        db_record = db.query(RecordOfMedicine).filter_by(ID=record_id).first()
        if not db_record:
            raise HTTPException(status_code=404, detail="记录不存在")
        
        # 获取原药品和数量
        original_medicine = db.query(Medicine).filter_by(ID=db_record.medicine_ID).first()
        original_number = db_record.number
        
        update_data = record_update.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_record, field, value)
        
        # 如果更新了药品ID或数量，需要调整库存
        if 'medicine_ID' in update_data or 'number' in update_data:
            new_medicine = db.query(Medicine).filter_by(ID=db_record.medicine_ID).first()
            if not new_medicine:
                raise HTTPException(status_code=404, detail="新药品不存在")
            
            # 还原原药品库存
            if original_medicine:
                original_medicine.stock += original_number
            
            # 扣除新药品库存
            if new_medicine.stock < db_record.number:
                raise HTTPException(status_code=400, detail="新药品库存不足")
            new_medicine.stock -= db_record.number
        
        db.commit()
        db.refresh(db_record)
        return db_record
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

# 删除药品发放记录（管理员或药师权限）
@router.delete("/{record_id}")
def delete_record(record_id: int,
                 db: Session = Depends(get_db),
                 user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    try:
        record = db.query(RecordOfMedicine).filter_by(ID=record_id).first()
        if not record:
            raise HTTPException(status_code=404, detail="记录不存在")
        
        # 恢复药品库存
        medicine = db.query(Medicine).filter_by(ID=record.medicine_ID).first()
        if medicine:
            medicine.stock += record.number
        
        db.delete(record)
        db.commit()
        return {"message": "记录删除成功"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/pharmacist-history/{pharmacist_id}")
def get_pharmacist_records(pharmacist_id: int,
                           db: Session = Depends(get_db),
                           user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))): # 确保只有管理员或药师可以查看
    """
    查看指定药剂师的历史发药记录。
    """
    # 验证请求的药剂师ID是否与当前登录用户ID匹配（如果是非管理员）
    if user["user_type"] == "PHARMACIST" and user['user_ref_id'] != pharmacist_id:
        raise HTTPException(status_code=403, detail="无权查看其他药剂师的记录")

    records = db.query(RecordOfMedicine).filter(RecordOfMedicine.phar_ID == pharmacist_id).all()
    if not records:
        return [] # 如果没有记录，返回空列表
    return records